package com.profgj.profgj.controller;

import com.profgj.profgj.entity.ProductYearEnergyconsumption;
import com.profgj.profgj.enums.ServerStatus;
import com.profgj.profgj.service.ProductYearEnergyconsumptionService;
import com.profgj.profgj.utils.EmptyUtils;
import com.profgj.profgj.utils.ReturnOperator;
import com.profgj.profgj.vo.*;
import io.swagger.annotations.*;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;
import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * (年能耗)控制层
 * 统计算法在ProductYearEnergyconsumptionServiceImpl类中实现
 * 产品年能耗数据的记录添加是经过产品的月能耗添加或者更变才进行 统计运算添加到数据中的
 * 是由ProductMonthEnergyController 中  POST和put 中 添加或更变 产品月记录之后 调用 updateYearStatistic函数在
 * 调用ProductYearEnergyconsumptionService 类中的方法实现 计算
 * 调用ProductYearEnergyconsumptionService 类中的方法实现 计算
 * @author 杨帅
 * @since 2021-06-22 11:09:35
 */


/**
 * JSON格式返回
 */
@RestController
/**
 * 请求基路径
 */
@RequestMapping("/yeg")
@Api(tags = {"年能耗"},description = "年能耗")
public class YearEnergyController {

    /**
     * 产品年统计服务对象
     */
    @Resource
    private ProductYearEnergyconsumptionService productYearEnergyconsumptionService;

    /**
     * 返回空对象的替代品
     */
    private EmptyObject emptyObject = new EmptyObject();


    /**
     *  id查询年能耗统计情况
     * @param id    年能耗id
     * @param session    会话对象 内部存储 user_id/user_name/role_id
     * @return
     */
    @GetMapping("/yearenergy/{id}")
    @ApiOperation(value = "id查询年能耗统计情况",produces = "application/json",consumes = "application/json")
    @ApiImplicitParam(name = "id",value = "年能耗id", required = true, dataType = "Integer", paramType = "Integer", dataTypeClass = Integer.class)
    @ApiResponses({
            @ApiResponse(code = 200, message = "表明该请求被成功地完成,所请求的资源发送到客户端"),
            @ApiResponse(code = 401, message = "请求要求身份验证,常见于需要登录而用户未登录的情况"),
            @ApiResponse(code = 403, message = "服务器拒绝请求,常见于机密信息或复制其它登录而用户未登录的情况"),
            @ApiResponse(code = 404, message = "服务器无法取得所请求的网页,请求资源不存在"),
            @ApiResponse(code = 500, message = "服务器内部错误")
    })
    public ResponseEntity<ResultMsg> yearEnergyQueryByIdMethod(@PathVariable("id") Long id,
                                                                @ApiIgnore HttpSession session){
        // 参数校验
        if (!EmptyUtils.isLongEmpty(id)) {
            return ReturnOperator.createResultMsg("", ServerStatus.ID_NOT_NULL, ServerStatus.ERROR,
                    new ArrayList(), emptyObject, HttpStatus.OK);
        }

        Integer role_id = Integer.parseInt(String.valueOf(session.getAttribute("role_id")));
        Integer user_id = Integer.parseInt(String.valueOf(session.getAttribute("user_id")));

        // id查询产品年信息
        ProductYearEnergyconsumptionVo productYearEnergyconsumptionVo = null;
        // 不是管理员的情况下
        if (role_id != 1) {
            productYearEnergyconsumptionVo = productYearEnergyconsumptionService.queryByIdAndUserId(id, user_id);
        } else {
            productYearEnergyconsumptionVo = productYearEnergyconsumptionService.queryById(id);
        }

        // 查询校验
        if (!EmptyUtils.isProductYearEnergyconsumptionEmpty(productYearEnergyconsumptionVo)){
            return ReturnOperator.createResultMsg("", ServerStatus.QUERY_MESSAGE_ERR, ServerStatus.ERROR,
                    new ArrayList(), emptyObject, HttpStatus.OK);
        }

        // 返回数据
        return ReturnOperator.createResultMsg(ServerStatus.QUERY_MESSAGE_SUCCESS, "", ServerStatus.OK,
                new ArrayList(), productYearEnergyconsumptionVo, HttpStatus.OK);
    }


    /**
     * 产品id查询产品年能耗
     * @param productId     产品id
     * @return
     */
    @GetMapping("/yearenergy/productid/{productId}")
    @ApiOperation(value = "产品id查询产品年能耗",produces = "application/json",consumes = "application/json")
    @ApiImplicitParam(name = "productId",value = "产品id", required = true, dataType = "Long", paramType = "Long", dataTypeClass = Long.class)
    @ApiResponses({
            @ApiResponse(code = 200, message = "表明该请求被成功地完成,所请求的资源发送到客户端"),
            @ApiResponse(code = 401, message = "请求要求身份验证,常见于需要登录而用户未登录的情况"),
            @ApiResponse(code = 403, message = "服务器拒绝请求,常见于机密信息或复制其它登录而用户未登录的情况"),
            @ApiResponse(code = 404, message = "服务器无法取得所请求的网页,请求资源不存在"),
            @ApiResponse(code = 500, message = "服务器内部错误")
    })
    public ResponseEntity<ResultMsg> yearEnergyQueryListByProductId(@PathVariable("productId") Long productId){
        // 参数校验
        if(!EmptyUtils.isLongEmpty(productId)){
            return ReturnOperator.createResultMsg("", ServerStatus.ID_NOT_NULL, ServerStatus.ERROR,
                    new ArrayList(), emptyObject, HttpStatus.OK);
        }

        // 产品id查询该产品下所有年能耗
        List<ProductYearEnergyconsumptionVo> productYearEnergyconsumptionVoList = productYearEnergyconsumptionService.queryListByProductId(productId);

        // 查询结果判断
        if (!EmptyUtils.isProductYearEnergyconsumptionListEmpty(productYearEnergyconsumptionVoList)){
            return ReturnOperator.createResultMsg("", ServerStatus.QUERY_MESSAGE_ERR, ServerStatus.ERROR,
                    new ArrayList(), emptyObject, HttpStatus.OK);
        }

        // 取最大整数位+1  2658 = 3000
        Long maxValue = operacionMaxValue(productYearEnergyconsumptionVoList);


        // 返回数据
        return ReturnOperator.createResultMsg(ServerStatus.QUERY_MESSAGE_SUCCESS, "", ServerStatus.OK,
                productYearEnergyconsumptionVoList, maxValue, HttpStatus.OK);
    }

    /**
     * 分页查询年能耗统计情况列表
     * @return
     */
    @GetMapping("/yearenergy/list")
    @ApiOperation(value = "查询年能耗统计情况列表",produces = "application/json",consumes = "application/json")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "draw",value = "绘制次数", required = true, dataType = "Integer", paramType = "Integer", dataTypeClass = Integer.class),
            @ApiImplicitParam(name = "start",value = "查询起始位置", required = true, dataType = "Integer", paramType = "Integer", dataTypeClass = Integer.class),
            @ApiImplicitParam(name = "length",value = "查询条数", required = true, dataType = "Integer", paramType = "Integer", dataTypeClass = Integer.class),
            @ApiImplicitParam(name = "search",value = "关键字", required = true, dataType = "String", paramType = "String", dataTypeClass = String.class)
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "表明该请求被成功地完成,所请求的资源发送到客户端"),
            @ApiResponse(code = 401, message = "请求要求身份验证,常见于需要登录而用户未登录的情况"),
            @ApiResponse(code = 403, message = "服务器拒绝请求,常见于机密信息或复制其它登录而用户未登录的情况"),
            @ApiResponse(code = 404, message = "服务器无法取得所请求的网页,请求资源不存在"),
            @ApiResponse(code = 500, message = "服务器内部错误")
    })
    public ResponseEntity<ReturnResult> yearEnergyQueryListMethod(Integer draw,
                                                                   Integer start,
                                                                   Integer length,
                                                                   String search,
                                                                   @ApiIgnore HttpSession session){
        // 参数校验
        if (!EmptyUtils.isIntegerEmpty(start) && !EmptyUtils.isIntegerEmpty(length)) {
            return ReturnOperator.createResultMsg(draw, 0,0,
                    new ArrayList(), HttpStatus.OK);
        }

        Integer role_id = Integer.parseInt(String.valueOf(session.getAttribute("role_id")));
        Integer user_id = Integer.parseInt(String.valueOf(session.getAttribute("user_id")));

        // id查询产品年信息
        List<ProductYearEnergyconsumptionVo> productYearEnergyconsumptionVoList = null;
        // 对产品年能耗list中的列单项进行统计存储对象
//        ProductYearEnergyconsumptionVoResult productYearEnergyconsumptionVoResult = null;
        Integer totalCount = 0;
        // 不是管理员的情况下
        if (role_id != 1) {

            if (EmptyUtils.isStringEmpty(search)) {
                totalCount = productYearEnergyconsumptionService.queryAllByKeywordAndUserId(search, user_id).size();
                productYearEnergyconsumptionVoList = productYearEnergyconsumptionService.queryAllByKeywordAndLimitAndUserId(search, start, length, user_id);
            } else {
                totalCount = productYearEnergyconsumptionService.queryAllByUserId(user_id).size();
                productYearEnergyconsumptionVoList = productYearEnergyconsumptionService.queryAllByLimitAndUserId(start, length, user_id);
            }

            // 对上一句查询的结果列 每项进行sum统计
//            productYearEnergyconsumptionVoResult = productYearEnergyconsumptionService.queryAllByLimitAndUserIdSumResult(offset, limit, user_id);
        } else {

            if (EmptyUtils.isStringEmpty(search)) {
                totalCount = productYearEnergyconsumptionService.queryAllByKeyword(search).size();
                productYearEnergyconsumptionVoList = productYearEnergyconsumptionService.queryAllByLimitAndKeyword(search, start, length);
            } else {
                totalCount = productYearEnergyconsumptionService.queryAll().size();
                productYearEnergyconsumptionVoList = productYearEnergyconsumptionService.queryAllByLimit(start, length);
            }

            // 对上一句查询的结果列 每项进行sum统计
//            productYearEnergyconsumptionVoResult = productYearEnergyconsumptionService.queryAllByLimitSumResult(offset, limit);
        }

        // 查询结果校验
        if (!EmptyUtils.isProductYearEnergyconsumptionListEmpty(productYearEnergyconsumptionVoList)) {
            return ReturnOperator.createResultMsg(draw, 0,0,
                    new ArrayList(), HttpStatus.OK);
        }

        // 返回数据
        return ReturnOperator.createResultMsg(draw, totalCount, totalCount,
                productYearEnergyconsumptionVoList,  HttpStatus.OK);
    }


    /**
     * 取list中能耗最大的值 取左边整数位+1
     * @param productYearEnergyconsumptionVoList
     * @return
     */
    private Long operacionMaxValue(List<ProductYearEnergyconsumptionVo> productYearEnergyconsumptionVoList){
        // 取一个 5个值中最大的值
        Double max = 0.0;

        for(ProductYearEnergyconsumptionVo productYearEnergyconsumptionVo : productYearEnergyconsumptionVoList){

            max = Double.parseDouble(String.valueOf(productYearEnergyconsumptionVo.getYearElectricityConsume()));

            if (max < productYearEnergyconsumptionVo.getYearCoalConsume()){
                max = productYearEnergyconsumptionVo.getYearCoalConsume();
            }
            if (max < productYearEnergyconsumptionVo.getYearFueloilConsume()){
                max = productYearEnergyconsumptionVo.getYearFueloilConsume();
            }
            if (max < productYearEnergyconsumptionVo.getYearNaturalgasConsume()){
                max = productYearEnergyconsumptionVo.getYearNaturalgasConsume();
            }
            if (max < productYearEnergyconsumptionVo.getYearWaterConsume()){
                max = productYearEnergyconsumptionVo.getYearWaterConsume();
            }

        }
        // 最大值转字符串
        String maxstr = max.toString();
        long maxL = 0;
        // 判断是否有小数位
        if (maxstr.indexOf('.') == -1){
            // 没有知己转
            maxL = Long.valueOf(maxstr);
        }else{
            // 有就截取小数点前面的
            String ii = maxstr.substring(0,maxstr.indexOf('.'));
            // 转成long值
            maxL = Long.parseLong(ii);
        }

        // 计算位数
        int wei = 0;
        while(maxL>10){
            maxL = maxL /10;
            wei++;
        }
        // 左边第一位+1
        maxL +=1;
        // 拼接0还原整数
        StringBuilder strB = new StringBuilder();
        strB.append(maxL);
        while(wei>0){
            strB.append("0");
            wei--;
        }
        // 转成long值
        return Long.valueOf(strB.toString());

    }
}
